<template>
  <div class="app-container">
    <basic-container>
      <div class="tag-tip">
        <el-tag color="#f08f00">审核中</el-tag>
        <el-tag color="#6bb377">已审核</el-tag>
        <el-tag color="#999">已结算</el-tag>
      </div>
      <el-row type="flex" justify="space-between">
        <el-col :span="4">
          <div class="room-content">
            <div class="room-title">大学教室列表</div>
            <div class="room-list" :class="{'active-list': item.roomId === activeNum}"
                 v-for="(item, index) in classRoomList" :key="index" @click="chooseRoom(item)">
              <span>{{ item.roomName }}</span>
              <i class="iconfont icon-eye" @click="seeDetail(item)"></i>
            </div>
          </div>
        </el-col>
        <el-col :span="19">
          <full-calendar
              ref="fullCalendar"
              :options="calendarOptions"
          >
          </full-calendar>
        </el-col>
      </el-row>
    </basic-container>
    <!-- 弹框 -->
    <el-dialog
        title="会议室预约"
        :visible.sync="dialogVisible"
        width="50%"
		:before-close="closeDialog"
    >
      <div>
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px">
          <el-row>
            <el-col :span="24">
              <el-form-item label="会议类型" style="width: 100%" prop="typeId">
                <el-select v-model="ruleForm.typeId" filterable placeholder="请选择" style="width: 100%">
                  <el-option
                      v-for="item in roomTypeList"
                      :key="item.purposeId"
                      :label="item.purposeName"
                      :value="item.purposeId">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="会议名称" style="width: 100%" prop="subject">
                <el-input v-model="ruleForm.subject" placeholder="请输入会议名称"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="会议申请原因" style="width: 100%" prop="memo">
                <el-input v-model="ruleForm.memo" placeholder="请输入会议申请原因"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="会议使用人" style="width: 100%" prop="typeId">
                <el-select v-model="ruleForm.applicantId" filterable placeholder="请选择会议使用人" style="width: 100%">
                  <el-option
                      v-for="item in roomTypeList"
                      :key="item.purposeId"
                      :label="item.purposeName"
                      :value="item.purposeId">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="联系方式" style="width: 100%" prop="extNo">
                <el-input v-model="ruleForm.extNo" placeholder="请输入联系方式"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="会议地点" style="width: 100%" prop="roomId">
                <el-select v-model="ruleForm.roomId" @change="change" placeholder="请选择会议地点" style="width: 100%">
                  <el-option
                      v-for="item in classRoomList"
                      :key="item.roomId"
                      :label="item.roomName"
                      :value="item.roomId">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="费用">
                <div class="p">
                    <span v-if="roomInfo && roomInfo.cost">
                        {{ `${roomInfo.cost}/h` }}
                    </span>
                </div>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="备注" style="width: 100%">
                <!-- <el-input v-model="roomInfo.remark" disabled ></el-input> -->
                <div class="p">
                    <span v-if="roomInfo && roomInfo.remark">
                        {{ roomInfo.remark }}
                    </span>
                </div>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="参与人数" prop="userNumber">
                <el-input type="number" min='1' v-model="ruleForm.userNumber"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="开始日期" style="width: 100%" prop="showStartDate">
                <el-date-picker
                v-model="ruleForm.showStartDate"
                type="date"
                value-format="yyyy-MM-dd"
                format="yyyy-MM-dd"
                @change="startDateChoose"
                :picker-options='pickerOptions1'
                style="width: 100%"
                placeholder="选择日期">
              </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-time-select
              v-model="ruleForm.showStartTime"
				default-value='10:00'
              :picker-options="{
                start: '00:00',
                step: '00:30',
                end: '23:30 ',
                minTime: minStartTime
              }"
              placeholder="选择时间">
            </el-time-select>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="结束日期" style="width: 100%" prop="showEndDate">
                <el-date-picker
                v-model="ruleForm.showEndDate"
				@change="endDateChoose"
                type="date"
                style="width: 100%"
                value-format="yyyy-MM-dd"
                format="yyyy-MM-dd"
                :picker-options='pickerOptions1'
                placeholder="选择日期">
              </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-time-select
				default-value='10:00'
              v-model="ruleForm.showEndTime"
              :picker-options="{
                start: '00:00',
                step: '00:30',
                end: '23:30 ',
                minTime: minEndTime
              }"
              placeholder="选择时间">
            </el-time-select>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="物资需求">
                <el-checkbox-group v-model="ruleForm.mrMaterialDtls">
                  <el-checkbox @change="checkChange(item)" v-for="item in materialList" :label="item.materialId"
                               :key="item.materialId">
                    {{ item.materialName }}
                  </el-checkbox>
                </el-checkbox-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="其他需求">
                <el-input
                    type="textarea"
                    :autosize="{ minRows: 2, maxRows: 4}"
                    placeholder="请输入其他需求"
                    v-model="ruleForm.otherRemark">
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
        <span slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="addEvents('ruleForm')">确 定</el-button>
        </span>
    </el-dialog>

    <!--教室详情弹出窗 start-->
    <el-dialog title="教室详情" width="550px" :close-on-click-modal="false" :visible.sync="dialogFormVisible"
               :before-close="close">
      <el-form :model="model" ref="ruleForm" label-width="120px">
        <el-form-item label="教室名称" prop="roomName">
          <el-input :value="model.roomName" disabled style="width: 350px"></el-input>
        </el-form-item>
        <el-form-item label="教室分类">
          <el-select v-model="model.typeId" disabled style="width: 350px">
            <el-option
                v-for="item in typeList"
                :key="item.typeId"
                :label="item.typeName"
                :value="item.typeId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="教室用途">
          <el-select v-model="model.purposeId" disabled style="width: 350px">
            <el-option
                v-for="item in purposeList"
                :key="item.purposeId"
                :label="item.purposeName"
                :value="item.purposeId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="教室设备">
          <el-input :value="model.eqName" disabled style="width: 350px"></el-input>
        </el-form-item>
        <el-form-item label="能源费">
          <el-input :value="model.cost + '.00'" disabled style="width: 350px"></el-input>
        </el-form-item>
        <el-form-item label="教室缩略图">
          <img style="width: 150px;height: 150px" :src="model.url" alt="">
        </el-form-item>
        <el-form-item label="备注">
          <el-input type="textarea" resize="none" :rows="4" disabled :value="model.remark" style="width: 350px"></el-input>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!--教室详情弹出窗 end-->
  </div>
</template>

<script>
import api from "@/api/classroom/classroom";
import {mapGetters} from "vuex";
// 教室日历组件
import FullCalendar from "@fullcalendar/vue";
import dayGridPlugin from "@fullcalendar/daygrid";
import interactionPlugin from "@fullcalendar/interaction";

export default {
  components: {
    FullCalendar, // make the <FullCalendar> tag available
  },
  data() {
    return {
		
		dialogFormVisible: false,
		model: {},
		equipmenteList: [], // 设备
		purposeList: [], // 用途
		typeList: [], // 分类
		pickerOptions1: {
			disabledDate(time) {
			let dateTime = new Date();
			let startDateTime = dateTime.setDate(dateTime.getDate() - 1);
			let endDateTime = dateTime.setDate(dateTime.getDate() + 15);
			return (
				time.getTime() < new Date(startDateTime).getTime() ||
				time.getTime() > new Date(endDateTime).getTime()
			);
			},
		},
		calendarApi: null,
		dialogVisible: false,
		classRoomList: [],
		roomTypeList: [],
		materialList: [],
		subList: [],
		roomInfo: {},
		activeNum: 0,
		tablePage: {
			total: 0,
			page: 1,
			size: 10,
			background: true,
			totalElements: 0,
		},
		minStartTime: '',
		minEndTime: '',
		ruleForm: {
			typeId: '',
			subject: '',
			memo: '',
			roomId: '',
			cost: '',
			userNumber: '',
			applicantId: 15864,
			beginDate: '',
			endDate: '',
			otherRemark: '',
			mrMaterialDtls: [],
			roomName: '',
			showStartDate: '',
			showStartTime: '',
			showEndDate: '',
			showEndTime: ''
		},
		calendarOptions: {
			//   timeGridPlugin  可显示每日时间段
			plugins: [dayGridPlugin, interactionPlugin],
			headerToolbar: {
			left: "prev,next today",
			center: "title",
			right: "dayGridMonth,dayGridWeek,dayGrid",
			// right: 'agendaWeek,dayGridWeek,dayGrid'
			},
			buttonText: {
			// 设置按钮
			today: "今天",
			month: "月",
			week: "周",
			dayGrid: "天",
			},
			// allDaySlot: false,
			editable: true,
			selectable: true,
			navLinks: true,

			// displayEventEnd: true,//所有视图显示结束时间
			initialView: "dayGridMonth", // 设置默认显示月，可选周、日
			dateClick: this.handleDateClick,
			eventClick: this.handleEventClick,
			eventsSet: this.handleEvents,
			select: this.handleDateSelect,
			// timezone
			// 设置日程
			events: [
			// {
			// 	id: 1,
			// 	title: '09:30~11:30 鲁会杰',
			// 	start: '2020-12-11',
			// 	end: '2020-12-11',
			// 	color: '#f08f00',
			// },
			// {
			// 	id: 2,
			// 	title: '9:30~14:30 鲁会杰',
			// 	start: '2020-12-14',
			// 	end: '2020-12-14',
			// 	color: '#6bb377',
			// },
			],
			eventColor: "#f08f00", // 修改日程背景色
			locale: "zh-cn", // 设置语言
			weekNumberCalculation: "ISO", // 周数
			customButtons: {
				prev: { // this overrides the prev button
					text: "PREV",
					click: () => {
						this.prev();
					}
				},
				next: { // this overrides the next button
					text: "PREV",
					click: () => {
						// let calendarApi = this.$refs.fullCalendar.getApi();
						// calendarApi.next();
						this.next();
					}
				},
				today: {
					text: "今天",
					click: () => {
						this.today();
					}
				}
			}
		},
		
		rules: {
			typeId: [
				{required: true, message: '请选择会议室类型', trigger: 'change'}
			],
			subject: [
				{required: true, message: '请输入会议名称', trigger: 'blur'}
			],
			memo: [
				{required: true, message: '请输入会议申请原因', trigger: 'blur'}
			],
			extNo: [
				{required: true, message: '请输入联系方式', trigger: 'blur'}
			],
			roomId: [
				{required: true, message: '请选择会议地点', trigger: 'change'}
			],
			userNumber: [
				{required: true, message: '请输入参与人数', trigger: 'blur'}
			],
			showStartDate: [
				{required: true, message: '请选择日期', trigger: 'change'}
			],
			showEndDate: [
				{required: true, message: '请选择日期', trigger: 'change'}
			],
			showStartTime: [
				{required: true, message: '请选择时间', trigger: 'change'}
			],
			showEndTime: [
				{required: true, message: '请选择时间', trigger: 'change'}
			]
		}
		};
  },
  created() {
    this.init();
  },
  mounted() {
    this.getCompList();
    this.getMaterial();
    this.calendarApi = this.$refs.fullCalendar.getApi();

  },
  computed: {
    ...mapGetters(["userInfo"]),
  },
  methods: {
    async init() {
      await this.getEquipmente();
      await this.getCompList();
      await this.getRoomList();
      await this.getPurpose();
      await this.getType();
    },
    // 选择开始时间
    startDateChoose() {
		// 最小开始时间： 1. 若选择当天 则需大于当前时间 2. 若大于当天 则可选择任意时间
		let now = new Date();
		let today = now.toISOString().substring(0,10);
		if (this.ruleForm.showStartDate === today) {
			this.minStartTime = `${new Date().getHours()}:${new Date().getMinutes()}`;
		} else {
			this.minStartTime = '';
		}
	},
	// 选择结束时间
	endDateChoose() {
		// 最小结束时间： 1.若开始时间等于结束时间 则需大于开始时间 2. 若不相等 则可选择任意时间
		if (this.ruleForm.showEndDate < this.ruleForm.showStartDate) {
			this.$message({
				message: '结束时间不能小于开始时间',
				type: 'warning'
			});
			this.ruleForm.showEndDate = '';
			return;
		}
		if (this.ruleForm.showStartDate == this.ruleForm.showEndDate) {
			this.minEndTime = this.ruleForm.showStartTime;
		} else {
			this.minEndTime = '';
		}
	},
    // 获取会议室列表
    getRoomList() {
      const params = {
        page: this.tablePage.page,
        size: 1000,
      };
      api.queryClassroomList(params, "get").then((res) => {
        this.classRoomList = res.content;
        this.activeNum = res.content[0].roomId;
        if (res.content && res.content && res.content.length) {
          this.getReservationList(res.content[0].roomId);
        }
        this.classRoomList.forEach((item) => {
          item.eqName = '';
          this.equipmenteList.forEach((itm) => {
            if (item.equipId.indexOf(itm.equipId) != -1) {
              item.eqName += `${itm.equipName},`;
            }
          })
        });
      });
    },
    // 获取设备
    getEquipmente() {
      const params = {}
      return api.queryEquipmente(params, 'get').then((res) => {
        this.equipmenteList = res.content;
      })
    },
    // 获取用途
    getPurpose() {
		const params = {}
		return api.queryRoomPurpose(params, 'get').then((res) => {
			this.purposeList = res.content;
		})
    },
    // 获取分类
    getType() {
		const params = {}
		return api.queryRoomType(params, 'get').then((res) => {
			this.typeList = res.content;
		})
    },
    // 点击查看教室详情
    seeDetail(val) {
		event.stopPropagation();
		this.dialogFormVisible = true;
		this.model = val;
    },
    // 获取教室类型列表
    getCompList() {
		const params = {
			page: this.tablePage.page,
			size: 1000,
		}
		api.queryRoomPurpose(params, 'get').then((res) => {
			this.roomTypeList = res.content;
		});
    },
    // 获取物资列表
    getMaterial() {
		const params = {
			page: this.tablePage.page,
			size: 1000,
		}
		api.queryMaterialList(params, 'get').then((res) => {
			this.materialList = res.content;
		});
    },
    // 选择会议室
    chooseRoom(value) {
		this.activeNum = value.roomId;
		// 查询该会议室下面的会议事件
		this.getReservationList(this.activeNum);
    },
    // 转换时间
    transDate(d) {
		var youWant = d.getFullYear() + '-' + (d.getMonth() + 1) + '-' + d.getDate() + ' ' + d.getHours() + '0:' + d.getMinutes() + '0:0' + d.getSeconds();
		return youWant;
    },
    // 获取教室下面的会议
    getReservationList(roomId) {
      // 此处应该改外不分页查询
		const params = {
			beginDate: this.transDate(this.calendarApi.currentData.viewApi.activeStart),
			endDate: this.transDate(this.calendarApi.currentData.viewApi.activeEnd),
			roomId,
			page: 1,
			size: 1000,
		};
		api.querySubscribeRoomList(params, "get").then((res) => {
			let newArr = [];
			this.subList = res.content;
			res.content.forEach((item) => {
				newArr.push({
				start: this.dealWithTime(item.beginDate),
				end: this.addDate(this.dealWithTime(item.endDate), 1),
				color: this.colorType(item.status),
				id: item.recordId,
				title: `${this.getTitle(item.beginDate, item.endDate)} ${item.applicantName}`,
				})
			});
			// console.log(newArr, 'newArr');
			this.calendarOptions.events = newArr;
		});
    },
    // 日期加1天
    addDate(date, days) {
		var d = new Date(date);
		d.setDate(d.getDate() + days);
		var m = d.getMonth() + 1;
		return `${d.getFullYear()}-${m}-${d.getDate()}`;
    },
    // 处理事件格式
    dealWithTime(date) {
		let newDate = /\d{4}-\d{1,2}-\d{1,2}/g.exec(date)[0];
		return newDate;
    },
    // 获取事件title
    getTitle(date1, date2) {
		let start = date1.substring(11, 16);
		let end = date2.substring(11, 16);
		return `${start}~${end}`;
    },
    // 根据会议室id 获取会议室详情
    change(roomId) {
		const params = {
			roomId
		};
		// 获取会议室name
		this.ruleForm.roomName = this.classRoomList.filter((item) => {return item.roomId === roomId})[0].roomName;
			api.queryRoomInfoWithId(params, 'get').then((res) => {
			this.roomInfo = res[0];
			this.ruleForm.cost = res[0].cost;
		});
    },
    handleEvents(events) {
      // console.log(events)
	},
	// 根据状态渲染不同的颜色
    colorType(status) {
		let result = null;
		switch (status) {
			case 2:
				result = 'rgb(240, 143, 0)';
				break;
			case 3:
				result = 'rgb(107, 179, 119)'
				break;
			case 7:
				result = 'rgb(153, 153, 153)'
				break;
			default:
				result = 'rgb(240, 143, 0)';
				break
			}
			return result;
    },
    // 切换上一个按钮
    prev() {
		this.calendarApi.prev();
		this.getReservationList(this.activeNum);
    },
    // 切换下一个按钮事件
    next() {
		this.calendarApi.next();
		this.getReservationList(this.activeNum);
    },
    // 点击今天按钮
    today() {
		this.calendarApi.today();
		this.getReservationList(this.activeNum);
		
    },
    // 物资多选框选择事件
    checkChange(data) {
      console.log(data);
    },
    // 处理物资list
    getMaterialList() {
		let arr = [];
		this.materialList.forEach((item) => {
			this.ruleForm.mrMaterialDtls.forEach((itm) => {
				if (item.materialId === itm) {
					arr.push(item);
				}
			})
		});
		//   return arr;
		this.ruleForm.mrMaterialDtls = arr;
	},
	// 点击日历
    handleDateClick: function (arg) {
		this.dialogVisible = true;
    },
    // 添加日历事件
    addEvents(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
			this.getMaterialList();
			//   this.ruleForm.mrMaterialDtls = this.getMaterialList();
			this.ruleForm.beginDate = `${this.ruleForm.showStartDate} ${this.ruleForm.showStartTime}`;
			this.ruleForm.endDate = `${this.ruleForm.showEndDate} ${this.ruleForm.showEndTime}`;
			console.log(this.ruleForm);
			api.queryRoomSubscribe(this.ruleForm).then((res) => {
				this.dialogVisible = false;
				this.$message({
				message: '预约成功！',
				type: 'success'
			});
				this.getReservationList(this.activeNum);
			})
        } else {
			console.log('error submit!!');
			return false;
        }
      });
    },
    // 日历事件点击事件
    handleEventClick(calEvent) {
		let id = calEvent.event.id;
		let info = this.subList.filter((item) => {return item.recordId == id});
		//获取当前会议详情
        this.dialogVisible = true;
        console.log(info[0])
        this.ruleForm = info[0];
		
    },
    handleDateSelect(selectInfo) {
      // console.log(selectInfo)
    },
    handleClose() {
    },
    //关闭教室详情弹窗
    close(){
		this.dialogFormVisible = false;
	},
	// 关闭会议室预约弹框
	closeDialog() {
		this.dialogVisible = false;
		this.$refs['ruleForm'].resetFields();
	}
  },
};
</script>

<style lang="scss" scoped>
@import "../../styles/classroom-style/classroom";

.el-col {
  margin-bottom: 0
}

.p {
  border-color: #EEE;
  cursor: not-allowed;
  -webkit-appearance: none;
  background-color: #FFF;
  background-image: none;
  border-radius: 4px;
  border: 1px solid #C3C3C3;
  box-sizing: border-box;
  color: #000;
  height: 32px;
  line-height: 32px;
  padding: 0 15px;
  width: 100%;
}

.active-list {
  background-color: #3AA1FF;
  color: #fff
}
</style>